import 'package:app/model/app_config.dart';
import 'package:app/model/model.dart';
import 'package:app/page/ReadBookPage.dart';
import 'package:app/router/router.dart';
import 'package:flutter/material.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class PageB extends StatefulWidget {
  const PageB({super.key});
  @override
  State<PageB> createState() => _State();
}

class _State extends State<PageB> {
  final cList = CountdownEventClassList.create();
  Widget buildItem(
    String title,
    int count,
    String content, {
    VoidCallback? onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 5),
        decoration: BoxDecoration(color: Colors.white),
        height: 50,
        child: Flex(
          direction: Axis.horizontal,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              constraints: BoxConstraints(minWidth: 100),
              padding: EdgeInsets.symmetric(horizontal: 10),
              child: Flex(
                direction: Axis.horizontal,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                spacing: 10,
                children: [
                  Text(title),
                  IntrinsicWidth(
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 6),
                      height: 22.5,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(11.25),
                        color: Color.fromARGB(220, 235, 233, 233),
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        count.toString(),
                        style: TextStyle(fontSize: 15),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Text(content),
          ],
        ),
      ),
    );
  }

  void eventsEdit(BuildContext context, CountdownEventClass event) async {
    if (event.name.value == "全部") return;
    final nameEditController = TextEditingController();
    nameEditController.text = event.name.value;
    showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        return TDInputDialog(
          textEditingController: nameEditController,
          title: "编辑倒数本名称",
          hintText: "请输入新名称",
          leftBtn: TDDialogButtonOptions(
            title: "取消",
            titleColor: const Color(0xE6000000),
            fontWeight: FontWeight.normal,
            action: () {
              Navigator.pop(dialogContext);
            },
            height: 56,
          ),
          rightBtn: TDDialogButtonOptions(
            title: "确定",
            action: () {
              if (nameEditController.text != event.name.value &&
                  nameEditController.text.trim() != "") {
                event.updateName(nameEditController.text);
              }
              Navigator.pop(dialogContext);
            },
            fontWeight: FontWeight.w600,
            height: 56,
          ),
        );
      },
    );
  }

  void deltaCountdownEventClass(
    BuildContext context,
    CountdownEventClass event,
  ) {
    if (cList.countdownEventList.length == 1) {
      TDToast.showFail(
        '至少保留一个倒数本',
        direction: IconTextDirection.vertical,
        context: context,
        maxLines: 3,
      );
      return;
    }
    showGeneralDialog(
      context: context,
      pageBuilder: (
        BuildContext buildContext,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return TDAlertDialog(
          content: '确定删除${event.name.value}吗？',
          rightBtnAction: () {
            if (cList.countdownEventList.length > 1) {
              cList.deleteCountdownEventClassWithChildren(event.id.value);
            }
            Navigator.of(buildContext).pop();
          },
          leftBtnAction: () {
            Navigator.of(buildContext).pop();
          },
        );
      },
    );
  }

  void addCountdownEventClass(BuildContext context) {
    final nameController = TextEditingController();
    showDialog(
      context: context,
      builder: (BuildContext dialogContext) {
        return TDInputDialog(
          textEditingController: nameController,
          title: "新建倒数本",
          hintText: "请输入名称",
          leftBtn: TDDialogButtonOptions(
            title: "取消",
            titleColor: const Color(0xE6000000),
            fontWeight: FontWeight.normal,
            action: () {
              Navigator.pop(dialogContext);
            },
            height: 56,
          ),
          rightBtn: TDDialogButtonOptions(
            title: "确定",
            action: () {
              if (nameController.text.trim() != "") {
                cList.addCountdownEventClass(nameController.text);
              }
              Navigator.pop(dialogContext);
            },
            fontWeight: FontWeight.w600,
            height: 56,
          ),
        );
      },
    );
  }

  Widget _buildEventList() {
    return Obx(() {
      return ListView.builder(
        itemCount: cList.countdownEventList.length + 1,
        itemBuilder: (context, index) {
          var screenWidth = MediaQuery.of(context).size.width;
          return Obx(() {
            CountdownEventClass? event;
            String eventName;
            int childrenCount = 0;
            if (index == 0) {
              eventName = "全部";
              event = null;
              childrenCount = cList.countdownEventList.fold(
                0,
                (value, element) => value + element.eventChildren.length,
              );
            } else {
              event = cList.countdownEventList[index - 1];
              eventName = event.name.value;
              childrenCount = event.eventChildren.length;
            }
            return Column(
              children: [
                LayoutBuilder(
                  builder: (context, constraints) {
                    return TDSwipeCell(
                      groupTag: 'book',
                      disabled: event == null,
                      right: TDSwipeCellPanel(
                        extentRatio: 180 / screenWidth,
                        children: [
                          TDSwipeCellAction(
                            flex: 20,
                            backgroundColor: Color(0xFFFA9550),
                            label: '编辑',
                            onPressed: (context) {
                              eventsEdit(context, event!);
                            },
                          ),
                          TDSwipeCellAction(
                            flex: 20,
                            backgroundColor: Color(0xFFD54941),
                            label: '删除',
                            onPressed: (context) {
                              deltaCountdownEventClass(context, event!);
                            },
                          ),
                        ],
                      ),
                      cell: buildItem(
                        eventName,
                        childrenCount,
                        "倒计时事件",
                        onTap: () {
                          if (event != null) {
                            context
                                .routeOf<ReadBookPage>()
                                .arguments(event)
                                .to();
                            return;
                          }
                          var allEvents = CountdownEventClass.create(
                            name: "全部",
                          );
                          allEvents.eventChildren.addAll(
                            cList.countdownEventList.fold(
                              [],
                              (value, element) => [
                                ...value,
                                ...element.eventChildren,
                              ],
                            ),
                          );
                          context
                              .routeOf<ReadBookPage>()
                              .arguments(allEvents)
                              .to();
                        },
                      ),
                    );
                  },
                ),
                if (index < cList.countdownEventList.length)
                  SizedBox(height: 10),
              ],
            );
          });
        },
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TDNavBar(
        height: 48,
        title: "倒数本",
        titleColor: Colors.white,
        centerTitle: false,
        backgroundColor: StaticAppConfig.appBarColor,
        titleFontWeight: FontWeight.w600,
        useDefaultBack: false,
        screenAdaptation: true,
        rightBarItems: [
          TDNavBarItem(
            icon: TDIcons.table_add,
            iconSize: 24,
            iconColor: Colors.white,
            action: () {
              addCountdownEventClass(context);
            },
          ),
        ],
      ),
      body: GestureDetector(
        onTap: () {
          TDSwipeCell.close('book');
        },
        child: Container(
          decoration: BoxDecoration(color: Color(0xFFCCCCCC)),
          child: _buildEventList(),
        ),
      ),
    );
  }
}
